package com.magic.interview.BFS.LC1162地图分析;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

/**
 * @author laoma
 * @create 2022-01-29 22:57
 */
public class Solution {
    public int maxDistance(int[][] grid) {
        int ans = -1;
        int n = grid.length;
        Queue<int[]> queue = new LinkedList<>();
        Map<Integer, Integer> map = new HashMap<>();
        // 通过所有的陆地 bfs
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    queue.add(new int[]{i, j});
                    map.put(i * n + j, 0);
                }
            }
        }
        int[][] dirs = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        while (!queue.isEmpty()) {
            int[] top = queue.poll();
            int x = top[0], y = top[1];
            int step = map.get(n * x + y);
            for (int[] dir : dirs) {
                int a = x + dir[0], b = y + dir[1];
                if (a < 0 || a >= n || b < 0 || b >= n) {
                    continue;
                }
                if (grid[a][b] != 0) {
                    // 表示已经被标记过
                    continue;
                }
                //  此处海洋到最近的陆地的距离
                grid[a][b] = step + 1;
                queue.add(new int[]{a, b});
                map.put(n * a + b, step + 1);
                ans = Math.max(ans, step + 1);
            }
        }
        return ans;
    }
}
